/*
 * Created on Tue Sep 26 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import type { CaptchaParam } from '../../types/CaptchaParam';
import type { CaptchaResult } from '../../types/CaptchaResult';
import { ErrorCode } from '../../constants';
import  { createError } from '../../utils/ErrorUtils';
import { isPhone, checkCaptchaBusiness } from '../../utils/CheckUtils';
import redis from '../../redis';
import { getCaptchaRedisKey } from '../../utils/CaptchaUtils';
import Random from 'random-js';
import type { ICaptchaSendStrategy } from './strategy/ICaptchaSendStrategy';
import CaptchaSendStrategy from './strategy';
import config from '../../config';

class CaptchaService {
  strategy: ICaptchaSendStrategy = CaptchaSendStrategy;

  async request(param: CaptchaParam): Promise<CaptchaResult> {
    if (!isPhone(param.phone)) {
      throw createError(400, '手机不合法', ErrorCode.PHONE_INVALID);
    }

    if (!checkCaptchaBusiness(param.business)) {
      throw createError(400, '业务类型非法', ErrorCode.CAPTCHA_BUSINESS_INVALID);
    }

    let key = getCaptchaRedisKey(param.phone, param.business);
    let captcha = (new Random()).integer(1000, 9999).toString();
    await this.strategy.send({
      captcha,
      phone: param.phone
    });
    //存储在redis中
    await redis.multi().set(key, captcha).expire(key, config.captcha.expireTime).execAsync();

    return {
      phone: param.phone,
      captcha: captcha,
      expire: config.captcha.expireTime,
      business: param.business
    }
  }
}

export default new CaptchaService();
